package com.geoway.adf.report.service.impl;

import com.geoway.adf.report.excel.sheet.Sheet;
import com.geoway.adf.report.excel.util.Converter;
import com.geoway.adf.report.excel.workbook.WorkBook;
import com.geoway.adf.report.po.SheetPO;
import com.geoway.adf.report.po.WorkBookPO;
import com.geoway.adf.report.service.ReportService;
import com.geoway.adf.report.service.SheetService;
import com.geoway.adf.report.service.WorkBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author: lzw
 * @Date: 2024/1/12 17:36
 * @Description:
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private WorkBookService workBookService;
    @Autowired
    private SheetService sheetService;
    @Override
    public WorkBook findById(String id) {
        Optional<WorkBookPO> workBookPO = workBookService.findById(id);
        List<SheetPO> sheets = sheetService.findByExcelId(id);
        if(!workBookPO.isPresent()){
            return new WorkBook();
        }else {
            WorkBook workBook = workBookPO.get().getWorkBook();
            workBook.setData(sheets.stream().map(sheetPO -> {
                Sheet sheet = sheetPO.getSheet();
                Converter.initCellData(sheet);
                return sheet;
            }).collect(Collectors.toList()));
            return workBook;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public WorkBook save(WorkBook workBook) {
        WorkBookPO workBookPO = workBookService.save(WorkBookPO.toWorkBookPO(workBook.clone()));
        List<SheetPO> collect = workBook.getData().stream().map(sheet -> SheetPO.toSheetPO(sheet,workBookPO.getExcelId())).collect(Collectors.toList());
        List<SheetPO> sheetPOS = sheetService.saveAll(collect);
        WorkBook wb = workBookPO.getWorkBook();
        wb.setData(sheetPOS.stream().map(sheetPO -> sheetPO.getSheet()).collect(Collectors.toList()));
        return wb;
    }
}
